<template>
  <div id="scenic-add">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="senic-ruleForm" size="small">
      <el-form-item label="景区名称" prop="name">
        <el-input v-model="ruleForm.name" :disabled="viewDetail" placeholder="请输入景区名称，长度2~30个字符"></el-input>
      </el-form-item>
      <el-form-item label="积分设置" prop="integralSet">
        <el-input v-model="ruleForm.integralSet" class="wideS-input" :disabled="viewDetail"></el-input>
        小时内入园多次仅记录一次
      </el-form-item>
      <el-form-item label="入园限制" >
          <el-form-item class="wideC-input" prop="gardenSet">
            <el-input v-model="ruleForm.gardenSet" class="wideS-input" :disabled="viewDetail"></el-input>
            小时内最多可入园
          </el-form-item>
          <el-form-item class="wideC-input" prop="gardenSetNum">
            <el-input v-model="ruleForm.gardenSetNum" class="wideS-input" :disabled="viewDetail"></el-input>
            次
          </el-form-item>
      </el-form-item>
      <el-form-item label="闸机ID" prop="gateMachineIds">
        <el-input v-model="ruleForm.gateMachineIds" :disabled="viewDetail" placeholder="支持数字和字母，多个ID可用英文逗号分隔"></el-input>
      </el-form-item>
      <el-form-item label="POS机ID" prop="posMachineIds">
        <el-input v-model="ruleForm.posMachineIds" :disabled="viewDetail" placeholder="支持数字和字母，多个ID可用英文逗号分隔"></el-input>
      </el-form-item>
      <el-form-item label="门市价" prop="price">
        <el-input v-model="ruleForm.price" :disabled="viewDetail" placeholder="请输入数字，最多保留小数点后两位"></el-input> 元
        <span class="tip">&nbsp;&nbsp;<i class="el-icon-info"></i> 如未设置产品的结算门市价，则使用此门市价</span>
      </el-form-item>
      <el-form-item label="保底价" prop="basePrice">
        <el-input v-model="ruleForm.basePrice" :disabled="viewDetail" placeholder="请输入数字，最多保留小数点后两位"></el-input> 元
        <span class="tip">&nbsp;&nbsp;<i class="el-icon-info"></i> 如未设置产品的结算保底价，则使用此保底价</span>
      </el-form-item>
      <el-form-item label="结算价格">
        <el-table
          :data="tableData"
          border
          style="width:600px"
          size="small">
          <el-table-column
            prop="productName"
            label="产品名称">
          </el-table-column>
          <el-table-column
            label="保底价（元）"
            width="190px"
            align="center">
            <template slot-scope="scope">
              <el-form :model="scope.row" size="small">
                <el-form-item
                  prop="basePrice"
                  :rules="[
						               { pattern: /^[0-9]{1,8}([.][0-9]{1,2})?$/, message: '请输入小数点后最多两位的数字', trigger: 'blur' } ]">
                  <el-input v-model="scope.row.basePrice" class="widTiny" :disabled="viewDetail"></el-input>
                </el-form-item>
              </el-form>
              <!--<el-form-item >-->
                <!--<el-input v-model="scope.row.basePrice" class="widTiny" :disabled="viewDetail"></el-input>-->
              <!--</el-form-item>-->
            </template>
          </el-table-column>
          <el-table-column
            label="门市价（元）"
            width="190px"
            align="center">
            <template slot-scope="scope">
              <el-form :model="scope.row" size="small">
                <el-form-item
                  prop="price"
                  :rules="[
						               { pattern: /^[0-9]{1,8}([.][0-9]{1,2})?$/, message: '请输入小数点后最多两位的数字', trigger: 'blur' } ]">
                  <el-input v-model="scope.row.price" class="widTiny" :disabled="viewDetail"></el-input>
                </el-form-item>
              </el-form>
                <!--<el-form-item >-->
                  <!--<el-input v-model="scope.row.price" class="widTiny" :disabled="viewDetail"></el-input>-->
                <!--</el-form-item>-->
            </template>
          </el-table-column>
          <el-table-column
            label="日历价格"
            align="center">
            <template slot-scope="scope">
              <div>
                <el-button type="primary" @click="openCalendar(scope.row.productId)" v-if="viewDetail">查看</el-button>
                <el-button type="primary" @click="openCalendar(scope.row.productId)" v-else>设置</el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm('ruleForm')" v-if="!this.isModify && !viewDetail">确认添加</el-button>
        <el-button type="primary" @click="modifyForm('ruleForm')" v-if="this.isModify && !viewDetail">确认修改</el-button>
        <el-button type="primary" @click="backScenicList()" v-if="!this.isModify && viewDetail">返回</el-button>
        <!--<el-button @click="resetForm('ruleForm')">重置</el-button>-->
      </el-form-item>
    </el-form>
    <el-dialog
      title="日历价格"
      width="800px"
      :visible.sync="calendarDialogVisible"
      @close="closeCalendar">
      <calendar-price
        v-if="updateCalendar"
        :calendarProp="calendarDataSet"
        :calendarSet="calendarDataSet.calendarData"
        @resetUpdate="resetUpdate"
        @calendarUpdate="calendarUpdate"
        :isPrdDetail="viewDetail">
      </calendar-price>
    </el-dialog>
  </div>
</template>
<script>
  import { Message } from 'element-ui'
  import { mapGetters } from 'vuex'
  import CalendarPrice from '@/components/CalendarPrice/calendarPrice.vue'
  import { addScenic, ModifyScenic, getScenicModifyData, getScenicProduct } from '@/api/scenicList'
  import _ from 'lodash'
  const today = new Date()
  let currentYear = today.getFullYear()
  let currentMonth = today.getMonth()
  let currentDate = today.getDate()
  const currentTodayObj = new Date(currentYear, currentMonth, currentDate)
  export default {
    computed: {
      ...mapGetters([
        'name',
        'roles'
      ])
    },
    components: {
      'calendar-price': CalendarPrice
    },
    data() {
      let payLimitHRange = (rule, value, callback) => {
        let reg = /^-?\d+$/
        if ((value < 0 || value > 999) && value) {
          callback(new Error('请输入0~999之间的整数'))
          return
        } else if (!reg.test(value) && value) {
          callback(new Error('请输入0~999之间的整数'))
          return
        } else {
          callback()
        }
      }
      return {
        viewDetail: false,
        isModify: false,
        ruleForm: {
          name: '',
          posMachineIds: null,
          gateMachineIds: null,
          integralSet: null,
          gardenSet: null,
          gardenSetNum: null,
          basePrice: null,
          price: null,
          id: null
        },
        rules: {
          name: [
            { required: true, message: '请输入景区名称', trigger: 'blur' },
            { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' }
          ],
          gateMachineIds: [
            { required: true, message: '请输入闸机ID', trigger: 'blur' }
          ],
          price: [
            { required: true, message: '请输入门市价', trigger: 'blur' },
            { pattern: /^[0-9]{1,8}([.][0-9]{1,2})?$/, message: '请输入数字，最多保留小数点后两位', trigger: 'blur' }
          ],
          basePrice: [
            { required: true, message: '请输入保底价', trigger: 'blur' },
            { pattern: /^[0-9]{1,8}([.][0-9]{1,2})?$/, message: '请输入数字，最多保留小数点后两位', trigger: 'blur' }
          ],
          integralSet: [
            { validator: payLimitHRange, trigger: 'blur' }
          ],
          gardenSet: [
            { validator: payLimitHRange, trigger: 'blur' }
          ],
          gardenSetNum: [
            { validator: payLimitHRange, trigger: 'blur' }
          ]
        },
        tableData: [],
        updateCalendar: true,
        calendarDialogVisible: false,
        calendarDataSet: {
//          effect_time_start: new Date(),
//          price: '8.00',
//          calendarData: [{
//            price: 99,
//            validDate: '2018-05-31'
//          }]
        }
      }
    },
    created() {
//      this.getProductType()
      let status = this.$route.query.status
      let queryId = this.$route.query.id
      if (status == 'edit') {
        this.getModifyData(queryId)
        this.isModify = true
        this.viewDetail = false
      } else if (status == 'check') {
        this.getModifyData(queryId)
        this.isModify = false
        this.viewDetail = true
      } else {
        this.getProductType()
        this.isModify = false
        this.viewDetail = false
      }
    },
    methods: {
      backScenicList() {
        this.$router.push({ path: '/scenicManage/scenicList' })
      },
      // 日历组件更新
      refreshCalendar() {
        this.updateCalendar = false
        this.$nextTick(() => {
          this.updateCalendar = true
        })
      },
      // 日历组件恢复SKU设置
      resetUpdate(dialogProp) {
        _.remove(this.calendarDataSet.calendarData, (calendarData) => {
          return _.indexOf(dialogProp.data, calendarData.validDate) != -1
        })
        this.refreshCalendar()
      },
      // 景区修改数据获取
      getModifyData(id) {
        let params = {
          id: id
        }
        getScenicModifyData(params).then(res => {
          let data = res.data
          this.tableData = []
          if (data.errorCode === 'E_000') {
            this.ruleForm.basePrice = data.body.basePrice
            this.ruleForm.gardenSet = data.body.gardenSet
            this.ruleForm.gardenSetNum = data.body.gardenSetNum
            this.ruleForm.gateMachineIds = data.body.gateMachineIds
            this.ruleForm.integralSet = data.body.integralSet
            this.ruleForm.name = data.body.name
            this.ruleForm.posMachineIds = data.body.posMachineIds
            this.ruleForm.price = data.body.price
//            this.ruleForm.cityId = data.body.cityId
//            this.ruleForm.provinceId = data.body.provinceId
            this.ruleForm.id = data.body.id
            if (data.body.scenicProductDtos.length > 0) {
              for (let i = 0; i < data.body.scenicProductDtos.length; i++) {
                let item = data.body.scenicProductDtos[i]
                let obj = {
                  basePrice: item.basePriceStr,
                  price: item.priceStr,
                  effect_time_start: currentTodayObj,
                  calendarData: item.productCalendarDtos,
                  productId: item.productId,
                  productName: item.productName
                }
                this.tableData.push(obj)
              }
            }
          }
        })
      },
      // 景区修改数据提交
      modifyForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let params = {
              id: this.ruleForm.id,
              basePrice: this.ruleForm.basePrice,
              cityId: 1,
              gardenSet: this.ruleForm.gardenSet,
              gardenSetNum: this.ruleForm.gardenSetNum,
              gateMachineIds: this.ruleForm.gateMachineIds,
              integralSet: this.ruleForm.integralSet,
              name: this.ruleForm.name,
              posMachineIds: this.ruleForm.posMachineIds,
              price: this.ruleForm.price,
              provinceId: 1,
              scenicProductDtos: []
            }
            let isReg = true
            for (let i = 0; i < this.tableData.length; i++) {
              let ele = this.tableData[i]
              let Reg = /^[0-9]{1,8}([.][0-9]{1,2})?$/
              if (ele.basePrice != '') {
                if (!Reg.test(ele.basePrice)) {
                  isReg = false
                  break
                }
              }
              if (ele.price != '') {
                if (!Reg.test(ele.price)) {
                  isReg = false
                  break
                }
              }
              let obj = {
                basePrice: ele.basePrice,
                price: ele.price,
                productId: ele.productId,
                productCalendarDtos: ele.calendarData
              }
              params.scenicProductDtos.push(obj)
            }
//            this.tableData.forEach(ele => {
//              let Reg = /^[0-9]{1,8}([.][0-9]{1,2})?$/
//              if (ele.basePrice != '' || ele.price != '') {
//                if (!Reg.test(ele.basePrice) || !Reg.test(ele.price)) {
//                  isReg = false
//                  return false
//                }
//              }
//              let obj = {
//                basePrice: ele.basePrice,
//                price: ele.price,
//                productId: ele.productId,
//                productCalendarDtos: ele.calendarData
//              }
//              params.scenicProductDtos.push(obj)
//            })
            if (!isReg) {
              Message({
                message: '产品保底价&门市价请输入数字，最多保留小数点后两位',
                type: 'warning',
                duration: 2 * 1000
              })
            } else {
              ModifyScenic(params).then(res => {
                let data = res.data
                if (data.errorCode === 'E_000') {
                  Message({
                    message: res.data.message,
                    type: 'success',
                    duration: 2 * 1000
                  })
                  this.$router.push({ path: '/scenicManage/scenicList' })
                }
              })
            }
          }
        })
      },
      // 景区添加数据提交
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let params = {
              basePrice: this.ruleForm.basePrice,
              cityId: 1,
              gardenSet: this.ruleForm.gardenSet,
              gardenSetNum: this.ruleForm.gardenSetNum,
              gateMachineIds: this.ruleForm.gateMachineIds,
              integralSet: this.ruleForm.integralSet,
              name: this.ruleForm.name,
              posMachineIds: this.ruleForm.posMachineIds,
              price: this.ruleForm.price,
              provinceId: 1,
              scenicProductDtos: []
            }
            let isReg = true
            for (let i = 0; i < this.tableData.length; i++) {
              let ele = this.tableData[i]
              let Reg = /^[0-9]{1,8}([.][0-9]{1,2})?$/
              if (ele.basePrice != '') {
                if (!Reg.test(ele.basePrice)) {
                  isReg = false
                  break
                }
              }
              if (ele.price != '') {
                if (!Reg.test(ele.price)) {
                  isReg = false
                  break
                }
              }
              let obj = {
                basePrice: ele.basePrice,
                price: ele.price,
                productId: ele.productId,
                productCalendarDtos: ele.calendarData
              }
              params.scenicProductDtos.push(obj)
            }
//            this.tableData.forEach(ele => {
//              let Reg = /^[0-9]{1,8}([.][0-9]{1,2})?$/
//              if (ele.basePrice != '') {
//                if (!Reg.test(ele.basePrice)) {
//                  isReg = false
//                  return false
//                }
//              }
//              if (ele.price != '') {
//                if (!Reg.test(ele.price)) {
//                  isReg = false
//                  return false
//                }
//              }
//               let obj = {
//                 basePrice: ele.basePrice,
//                 price: ele.price,
//                 productId: ele.productId,
//                 productCalendarDtos: ele.calendarData
//               }
//              params.scenicProductDtos.push(obj)
//            })
            if (!isReg) {
              Message({
                message: '产品保底价&门市价请输入数字，最多保留小数点后两位',
                type: 'warning',
                duration: 2 * 1000
              })
            } else {
              addScenic(params).then(res => {
                let data = res.data
                if (data.errorCode === 'E_000') {
                  Message({
                    message: res.data.message,
                    type: 'success',
                    duration: 2 * 1000
                  })
                  this.$router.push({ path: '/scenicManage/scenicList' })
                }
              })
            }
          }
        })
      },
      // 日历组件关闭时将日历数组数据赋值到table对应的产品Id
      closeCalendar() {
        this.tableData.forEach((ele, index) => {
          if (ele.productId == this.calendarDataSet.productId) {
            this.tableData[index].calendarData = _.cloneDeep(this.calendarDataSet.calendarData)
          }
        })
        this.calendarDataSetInit()
      },
      // 景区添加时获取景区产品类型
      getProductType() {
        getScenicProduct().then(res => {
          let data = res.data
          if (data.errorCode === 'E_000') {
            this.tableData = []
            if (data.body.length > 0) {
              for (let i = 0; i < data.body.length; i++) {
                let ele = data.body[i]
                let obj = {
                  basePrice: '',
                  price: '',
                  effect_time_start: currentTodayObj,
                  calendarData: [],
                  productId: ele.productId,
                  productName: ele.productName
                }
                this.tableData.push(obj)
              }
//              data.body.forEach(ele => {
//                let obj = {
//                  basePrice: '0.00',
//                  price: '0.00',
//                  effect_time_start: new Date(todayStr),
//                  calendarData: [],
//                  productId: ele.productId,
//                  productName: ele.productName
//                }
//                this.tableData.push(obj)
//              })
            }
          }
        })
      },
      // 对应的产品类型设置日历时将产品对应的日历数据赋值到组件calendarDataSet
      openCalendar(id) {
        this.tableData.forEach((ele) => {
          if (ele.productId == id) {
            let Reg = /^[0-9]{1,8}([.][0-9]{1,2})?$/
            if (ele.basePrice != '') {
              if (!Reg.test(ele.basePrice)) {
                Message({
                  message: '产品保底价&门市价请输入数字，最多保留小数点后两位',
                  type: 'warning',
                  duration: 2 * 1000
                })
                return false
              }
            }
            if (ele.price != '') {
              if (!Reg.test(ele.price)) {
                Message({
                  message: '产品保底价&门市价请输入数字，最多保留小数点后两位',
                  type: 'warning',
                  duration: 2 * 1000
                })
                return false
              }
            }
//            this.calendarDataSet.basePrice = ele.basePrice
//            this.calendarDataSet.price = ele.price
//            this.calendarDataSet.effect_time_start = ele.effect_time_start
//            this.calendarDataSet.calendarData = _.cloneDeep(ele.calendarData)
//            this.calendarDataSet.productId = ele.productId
//            this.calendarDataSet.productName = ele.productName
            this.calendarDataSet = _.cloneDeep(ele)
            this.refreshCalendar()
            this.calendarDialogVisible = true
            return
          }
        })
      },
      // 日历默认值初始化
      calendarDataSetInit() {
        this.calendarDataSet = {
          basePrice: '',
          price: '',
          effect_time_start: currentTodayObj,
          calendarData: [],
          productId: null,
          productName: null
        }
      },
      // 日历设置后自动更新
      calendarUpdate(dialogPops) {
        dialogPops.forEach((dialogProp) => {
          let update = {
            validDate: dialogProp.validDate,
            price: dialogProp.price
          }
          let existCalendarData = _.find(this.calendarDataSet.calendarData, (o) => {
            return o.validDate === dialogProp.validDate
          })
          if (existCalendarData) {
            this.$set(existCalendarData, 'price', dialogProp.price)
          } else {
            this.calendarDataSet.calendarData.push(update)
          }
        })
//        this.calendarDataSet.calendarData = this.calendarDataSet.calendarData.concat(dialogPops)
        this.refreshCalendar()
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss">
  #scenic-add{
    .senic-ruleForm{
      .tip{
        font-size: 12px;
        color:#888;
      }
      .el-input{
        width:280px;
        .el-input__inner{
          width:280px;
        }
      }

      .wideS-input{
        width:78px;
        .el-input__inner{
          width:78px;
        }
      }
      .widTiny{
        width:170px;
        .el-input__inner{
          width:170px;
        }
      }
      .wideC-input{
        display: inline-block;
        margin-bottom: 0;
        .el-form-item__content{
          width:197px;
        }
      }
      .el-table--small td{
        padding-bottom: 0;
      }
      .el-table--small{
        .el-form-item--small.el-form-item{
          /*margin-bottom: 0;*/
        }
      }
    }



  }
</style>
